package com.itheima.service.impl;


import com.itheima.common.BaseContext;
import com.itheima.common.constant.LoginConstant;
import com.itheima.dto.UserLoginDTO;
import com.itheima.entity.SysDict;
import com.itheima.entity.SysMenu;
import com.itheima.entity.SysUser;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.*;
import com.itheima.service.IndexService;
import com.itheima.utils.IpUtils;
import com.itheima.utils.JwtUtil;
import com.itheima.vo.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * IndexServiceImpl
 *
 * @author liliudong
 * @version 1.0
 * @description
 * @date 2023/7/26 17:48
 */
@Service
@RequiredArgsConstructor
public class IndexServiceImpl implements IndexService {

    private final JwtUtil jwtUtil;
    private final IpUtils ipUtils;

    private final SysUserMapper sysUserMapper;
    private final SysRoleMapper sysRoleMapper;
    private final SysMenuMapper sysMenuMapper;
    private final SysDictMapper sysDictMapper;
    private final SysMapper sysMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        SysUser sysUser = sysUserMapper.selectByUserName(userLoginDTO.getLogin_name());
        if (Objects.isNull(sysUser)) {
            throw new BusinessException("账号不正确");
        }
        String digest = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        if (!Objects.equals(digest, sysUser.getPassword())) {
            throw new BusinessException("密码不正确");
        }
        sysUser.setLoginIp(ipUtils.getClientIp());
        sysUser.setLoginDate(LocalDateTime.now());
        sysUser.setUpdateDate(LocalDateTime.now());
        sysUserMapper.updateById(sysUser);

        HashMap<String, Object> map = new HashMap<>(8);
        map.put(LoginConstant.USER_ID, sysUser.getId());
        String jwt = jwtUtil.createJWT(map);
        return UserLoginVO.builder().token(jwt).build();
    }

    @Override
    public ProfileVO profile() {
        ProfileVO profileVO = new ProfileVO();

        SysUser sysUser = sysUserMapper.selectById(BaseContext.getLoginUserId());
        String roleId = sysUser.getRoleId();

        UserInfoVO userInfoVO = new UserInfoVO();

        userInfoVO.setLogin_name(sysUser.getLoginName());
        userInfoVO.setName(sysUser.getName());
        userInfoVO.setEmail(sysUser.getEmail());
        userInfoVO.setPhone(sysUser.getPhone());
        userInfoVO.setLogin_ip(sysUser.getLoginIp());
        userInfoVO.setLogin_date(sysUser.getLoginDate());
        userInfoVO.setCreate_date(sysUser.getCreateDate());
        userInfoVO.setUpdate_date(sysUser.getCreateDate());
        userInfoVO.setDel_flag(sysUser.getDelFlag());
        userInfoVO.setStatus(sysUser.getStatus());
        userInfoVO.setId(sysUser.getId());

        ArrayList<String> roleIdList = new ArrayList<>();
        if (roleId != null) {
            String str = roleId.substring(2, roleId.length() - 2);
            String[] split = str.split(",");
            roleIdList.addAll(Arrays.asList(split));
            userInfoVO.setRole_id(roleIdList);
            List<String> roleNameList = sysRoleMapper.selectNameListByIds(roleIdList);
            userInfoVO.setRolename(roleNameList);
        }

        List<SysMenu> sysMenus = sysMenuMapper.selectListByRoleIds(userInfoVO.getRole_id());
        List<MenuVO> menuVOList = new ArrayList<>();
        sysMenus.forEach(sysMenu -> {
            MenuVO menuVO = new MenuVO();
            menuVO.setId(sysMenu.getId());
            menuVO.setPid(sysMenu.getPid());
            menuVO.setPath(sysMenu.getPath());
            menuVO.setComponent(sysMenu.getComponent());
            menuVO.setTitle(sysMenu.getTitle());
            menuVO.setIcon(sysMenu.getIcon());
            menuVO.setIs_show(sysMenu.getIsShow());
            menuVO.setIs_cache(sysMenu.getIsCache());
            menuVO.setIs_link(sysMenu.getIsLink());
            menuVO.setRedirect(sysMenu.getRedirect());
            menuVO.setCreateDate(sysMenu.getCreateDate());
            menuVO.setUpdateDate(sysMenu.getUpdateDate());
            menuVO.setDel_flag(sysMenu.getDelFlag());
            menuVO.setType(sysMenu.getType());
            menuVO.setSort(sysMenu.getSort());
            menuVO.setMark(sysMenu.getMark());
            menuVOList.add(menuVO);
        });

        HashMap<String, Object> result = new HashMap<>(16);
        List<SysDict> sysDictList = sysDictMapper.selectList();
        sysDictList.forEach(sysDict -> {
            HashMap<String, Object> item = new HashMap<>(8);
            item.put(sysDict.getValue(), sysDict.getLabel());
            result.put(sysDict.getType(), item);
        });

        ArrayList<String> btnList = new ArrayList<>();
        btnList.add("*");

        profileVO.setUserInfo(userInfoVO);
        profileVO.setMenuList(menuVOList);
        profileVO.setDictsList(result);
        profileVO.setBtnList(btnList);

        return profileVO;
    }

    @Override
    public ConfigVO getConfig() {
        List<String> str = sysMapper.selectSystem("system");
        System.out.println(str);
        ConfigVO configVO = new ConfigVO();
        for (int i = 0; i < str.size(); i++) {
            String value = str.get(i);
            if (i == 0) {
                configVO.setLogin_title(value);
            } else if (i == 1) {
                configVO.setLogin_bg(value);
            } else if (i == 2) {
                configVO.setSystem_name(value);
            } else if (i == 3) {
                configVO.setSystem_logo(value);
            } else if (i == 4) {
                configVO.setWeb_ico(value);
            }
        }
        return configVO;
    }


    @Override
    public HomeVO baseInfoConfig() {
        HomeVO homeVO = new HomeVO();
        List<CateVO> cateList = sysMapper.selectCate();
        List<CateVO> cateVOList = new ArrayList<>();
        cateList.forEach(cate -> {
            CateVO configVO = new CateVO();
            BeanUtils.copyProperties(cate, configVO);
            Integer num = sysMapper.getNum(cate.getId());
            configVO.setNum(num);
            cateVOList.add(configVO);
        });
        Integer advposNum = sysMapper.selectAdvpos();
        Integer tagNum = sysMapper.selectTag();
        Integer adminNum = sysMapper.selectAdmin();
        Integer articleNum = sysMapper.selectArticle();
        Integer cateNum = sysMapper.selectCates();
        Integer advimgNum = sysMapper.selectAdvimg();

        List<NewUserVO> newUserList = sysMapper.selectUsers();
        List<HotArticleVO> hotArticleList = sysMapper.selectArticles();

        UserVO userVO = new UserVO();
        Integer users = sysMapper.selectUser();
        userVO.setTotal(users);
        for (int i = 0; i < 2; i++) {
            Integer user = sysMapper.selectSexUser(i);
            if (i == 0) {
                userVO.setUser_man(user);
            } else {
                userVO.setUser_woman(user);
            }
        }
        homeVO.setAll_cate(cateVOList);
        homeVO.setAdvpos_num(advposNum);
        homeVO.setTag_num(tagNum);
        homeVO.setAdmin_num(adminNum);
        homeVO.setArticle_num(articleNum);
        homeVO.setCate_num(cateNum);
        homeVO.setAdvimg_num(advimgNum);
        homeVO.setNew_user(newUserList);
        homeVO.setHot_article(hotArticleList);
        homeVO.setUser(userVO);
        return homeVO;
    }
}
